package com.jerei.web.utils.spring;

import com.jerei.web.utils.UtilsUI;
import com.jerei.web.utils.UtilsWeb;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * Created by sunfeihu on 2016/10/21.
 */
@Controller
@RequestMapping(value = "/admin")
public class AdminDefaultControl extends AdminBaseControl {

    @Autowired
    private CookieLocaleResolver cookieLocaleResolver;

    @RequestMapping(value = "/changeLanguage", method = RequestMethod.GET)
    @ResponseBody
    public String language(HttpServletRequest request, String lang, HttpServletResponse response) {
        if (lang.equals("en")) {
            Locale locale = new Locale("en", "US");
            cookieLocaleResolver.setLocale(request, response, locale);
        } else if (lang.equals("pt")) {
            Locale locale = new Locale("pt", "PT");
            cookieLocaleResolver.setLocale(request, response, locale);
        } else {
            Locale locale = new Locale("zh", "CN");
            cookieLocaleResolver.setLocale(request, response, locale);
        }
        return UtilsUI.ok();
    }

    @RequestMapping(value = "/resources/plugins/{lang}/ueditor/dialogs/{name1}/{name2}.do", method = RequestMethod.GET)
    public String path(@PathVariable String name1, @PathVariable String name2, @PathVariable String lang, Model model, HttpServletRequest request) {
        model.addAttribute("domain", UtilsWeb.getDomain(request));
        return "/admin/resources/plugins/" + lang + "/ueditor/dialogs/" + name1 + "/" + name2;
    }


    @RequestMapping(value = "/export", method = RequestMethod.POST)
    @RequiresPermissions("*:export")
    public ModelAndView exoprt(ModelMap model, HttpServletRequest request) {
        String data = UtilsWeb.getString(request, "data", false);
        String fields = UtilsWeb.getString(request, "fields", false);
        String options = UtilsWeb.getString(request, "options", false);
        model.addAttribute("data", data);
        model.addAttribute("fields", fields);
        model.addAttribute("options", options);
        return new ModelAndView(new BaseExcelView(), model);
    }

}